/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.msk.base.service.goodsMember;

import com.google.common.collect.Lists;
import com.msk.base.domain.goodsMember.GoodsMember;
import com.msk.base.mapper.goodsMember.GoodsMemberDao;
import com.msk.common.exception.ServiceException;
import com.msk.common.utils.HtAssert;
import com.msk.common.utils.StringUtils;
import com.msk.sys.domain.Office;
import com.msk.sys.domain.Role;
import com.msk.sys.domain.User;
import com.msk.sys.mapper.UserDao;
import com.msk.sys.service.CrudService;
import com.msk.sys.service.OfficeService;
import com.msk.sys.service.SystemService;
import com.msk.wlhy.domain.Area;
import com.msk.wlhy.domain.HtCompany;
import com.msk.wlhy.mapper.HtCompanyDao;
import com.msk.wlhy.service.HtCompanyService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>[]</p>
 * <p>作者：lh</p>
 * <p>邮箱：lh@xiangyou.com</p>
 * <p>创建时间： 2018-11-30 </p>
 * <p>类说明：Service </p>
 * <p>修改记录：</p>
 */
@Service
@Transactional(readOnly = true)
public class GoodsMemberService extends CrudService<GoodsMemberDao, GoodsMember> {

	@Autowired
	private SystemService systemService;
	@Autowired
	private HtCompanyService htCompanyService;
    @Autowired
    private HtCompanyDao htCompanyDao;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private GoodsMemberDao goodsMemberDao;
	@Autowired
	private UserDao userDao;

	public GoodsMember get(String id) {
		return super.get(id);
	}

	public List<GoodsMember> findList(GoodsMember goodsMember) {
		return super.findList(goodsMember);
	}

//	public Page<GoodsMember> findPage(Page<GoodsMember> page, GoodsMember goodsMember) {
//		goodsMember.getSqlMap().put("dsf", BaseService.dataScopeFilter(goodsMember.getCurrentUser(), "o4", "u1"));
//		return super.findPage(page, goodsMember);
//	}

	@Transactional(readOnly = false)
	public void save(GoodsMember goodsMember) {
		User registerUser = goodsMember.getUser();
		User user = null;
		if(registerUser!=null && registerUser.getLoginName()!=null ){
			user = systemService.getUserByLoginName(registerUser.getLoginName());
		}else{
			if(registerUser!=null && registerUser.getId()!=null){
				user = systemService.getUser(registerUser.getId());
			}else if(goodsMember!=null && StringUtils.isNotBlank( goodsMember.getId())) {
				GoodsMember goodsMemberOld = this.get(goodsMember.getId());
				user = systemService.getUser(goodsMemberOld.getUser().getId());
			}
		}

		// 获取企业用户单位和企业管理员角色
		//Office office = OfficeUtils.getOfficeByCode("xiangyou_reg_dept");
		Role r = systemService.getRoleByEnname("goodsMember");
		List<Role> roleList= null;
		roleList = Lists.newArrayList();
		if(user == null){
			user = new User();
			// 是否允许登录
			user.setLoginFlag("y");
			// 注册人员
			user.setUserType("1");
			user.setUserIdentity("2");
			user.setMobile(goodsMember.getMobile());
			user.setPhone(goodsMember.getMobile());
			user.setNo(goodsMember.getMobile());
			if(registerUser!=null && StringUtils.isNotBlank(registerUser.getLoginName())){
				user.setLoginName(registerUser.getLoginName());
				user.setPassword(SystemService.entryptPassword(registerUser.getPassword()));
			}else {
				if(StringUtils.isBlank(goodsMember.getMobile())){
					user.setLoginName(goodsMember.getContactsPhone());
				}else{
					user.setLoginName(goodsMember.getMobile());
				}
				//如果用户不存在则默认密码为123456
				user.setPassword(SystemService.entryptPassword("123456"));
			}
			// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
			/*User currentUser = UserUtils.getUser();//当前登录人
			if(currentUser != null){*/
				//String companyId =currentUser.getCompany().getId();
			Office parent = new Office();
			parent.setId("0");
			Office office = new Office();
			office.setParent(parent);
			office.setType("");
			List<Office> officeList = officeService.findListOnly(office);
			if(officeList!=null && officeList.size()!=0){
				office = officeList.get(0);
				if(office!=null && office.getId()!=null){
					user.setCompany(office);
					user.setOffice(office);
					goodsMember.setOffice(office);
					goodsMember.setCompany(office);
				}else{
					Office office1 = new Office();
					office1.setId("1");
					user.setCompany(office1);
					user.setOffice(office1);
					goodsMember.setOffice(office1);
					goodsMember.setCompany(office1);
				}
			}
			roleList.add(r);
			user.setRoleList(roleList);
		}else{
			//每次用户名变更后需要清空以前用户名对应的用户缓存
			user.setOldLoginName(user.getLoginName());
			if(registerUser!=null && StringUtils.isNotBlank(registerUser.getLoginName())){
				user.setLoginName(registerUser.getLoginName());
			}else{
				user.setLoginName(goodsMember.getMobile());
			}
		}
		if(StringUtils.isBlank(goodsMember.getName())){
			goodsMember.setName(goodsMember.getContactsName());
		}else{
			user.setName(goodsMember.getName());
			goodsMember.setName(goodsMember.getName());
		}
		try{
			systemService.saveUser(user);
			goodsMember.setUser(user);
		}catch(ServiceException e){
			System.out.println(e.getMessage());
		}
		if(StringUtils.isEmpty(goodsMember.getId())){
			HtCompany htCompany = new HtCompany();
			HtCompany htCompany1 = null;
			if(StringUtils.isNotBlank(goodsMember.getComName())){
				htCompany.setCompanyName(goodsMember.getComName());
				htCompany1 = htCompanyService.getByName(htCompany);
			}
			if(htCompany1 == null){
				htCompany.setOffice(goodsMember.getOffice());
				htCompany.setCompany(goodsMember.getCompany());
				htCompanyService.save(htCompany);
				goodsMember.setCompany1(htCompany);
			}else{
				goodsMember.setCompany1(htCompany1);
			}
		}else{
			HtCompany htCompany = htCompanyService.get(goodsMember.getCompany1());
			if(htCompany!=null) {
				htCompany.setCompanyName(goodsMember.getComName());
				htCompanyService.save(htCompany);
			}
		}
		super.save(goodsMember);
	}


	@Transactional(readOnly = false)
	public void saveApplet(GoodsMember goodsMember) {
		User registerUser = goodsMember.getUser();
		User user = null;
		if(registerUser!=null && registerUser.getLoginName()!=null ){
			user = systemService.getUserByLoginName(registerUser.getLoginName());
		}else{
			if(registerUser!=null && registerUser.getId()!=null){
				user = systemService.getUser(registerUser.getId());
			}else if(goodsMember!=null && StringUtils.isNotBlank( goodsMember.getId())) {
				GoodsMember goodsMemberOld = this.get(goodsMember.getId());
				user = systemService.getUser(goodsMemberOld.getUser().getId());
			}
		}

		// 获取企业用户单位和企业管理员角色
		//Office office = OfficeUtils.getOfficeByCode("xiangyou_reg_dept");
		Role r = systemService.getRoleByEnname("goodsMember");
		List<Role> roleList= null;
		roleList = Lists.newArrayList();
		if(user == null){
			user = new User();
			// 是否允许登录
			user.setLoginFlag("y");
			// 注册人员
			user.setUserType("1");
			user.setUserIdentity("2");
			user.setMobile(goodsMember.getMobile());
			user.setPhone(goodsMember.getMobile());
			user.setNo(goodsMember.getMobile());
			if(registerUser!=null && StringUtils.isNotBlank(registerUser.getLoginName())){
				user.setLoginName(registerUser.getLoginName());
				user.setPassword(SystemService.entryptPassword(registerUser.getPassword()));
			}else {
				if(StringUtils.isBlank(goodsMember.getMobile())){
					user.setLoginName(goodsMember.getContactsPhone());
				}else{
					user.setLoginName(goodsMember.getMobile());
				}
				//如果用户不存在则默认密码为123456
				user.setPassword(SystemService.entryptPassword("123456"));
			}
			// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
			/*User currentUser = UserUtils.getUser();//当前登录人
			if(currentUser != null){*/
			//String companyId =currentUser.getCompany().getId();
			Office parent = new Office();
			parent.setId("0");
			Office office = new Office();
			office.setParent(parent);
			office.setType("");
			List<Office> officeList = officeService.findListOnly(office);
			if(officeList!=null && officeList.size()!=0){
				office = officeList.get(0);
				if(office!=null && office.getId()!=null){
					user.setCompany(office);
					user.setOffice(office);
					goodsMember.setOffice(office);
					goodsMember.setCompany(office);
				}else{
					Office office1 = new Office();
					office1.setId("1");
					user.setCompany(office1);
					user.setOffice(office1);
					goodsMember.setOffice(office1);
					goodsMember.setCompany(office1);
				}
			}
			roleList.add(r);
			user.setRoleList(roleList);
		}else{
			//每次用户名变更后需要清空以前用户名对应的用户缓存
			user.setOldLoginName(user.getLoginName());
			if (registerUser != null && StringUtils.isNotBlank(registerUser.getLoginName())) {
				user.setLoginName(registerUser.getLoginName());
			} else {
				user.setLoginName(goodsMember.getMobile());
			}
		}
		if(StringUtils.isBlank(goodsMember.getName())){
			goodsMember.setName(goodsMember.getContactsName());
		}else{
			user.setName(goodsMember.getName());
			goodsMember.setName(goodsMember.getName());
		}
		try {
			systemService.saveNewUser(user);
			goodsMember.setUser(user);
		} catch (ServiceException e) {
			System.out.println(e.getMessage());
		}
		super.save(goodsMember);
	}

	@Transactional(readOnly = false)
	public void saveOnly(GoodsMember goodsMember) {
		try{
			Office parent = new Office();
			parent.setId("0");
			Office office = new Office();
			office.setParent(parent);
			office.setType("");
			List<Office> officeList = officeService.findListOnly(office);
			if(officeList!=null && officeList.size()!=0){
				office = officeList.get(0);
				if(office!=null && office.getId()!=null){
					goodsMember.setOffice(office);
					goodsMember.setCompany(office);
				}else{
					Office office1 = new Office();
					office1.setId("1");
					goodsMember.setOffice(office1);
					goodsMember.setCompany(office1);
				}
			}
			goodsMember.setName(goodsMember.getContactsName());
			if(StringUtils.isEmpty(goodsMember.getId())){
				if(StringUtils.isNotEmpty(goodsMember.getComName())){
					HtCompany htCompany = new HtCompany();
					htCompany.setCompanyName(goodsMember.getComName());
					HtCompany htCompany1 = htCompanyService.getByName(htCompany);
					if(htCompany1 == null){
						htCompany.setOffice(goodsMember.getOffice());
						htCompany.setCompany(goodsMember.getCompany());
						htCompanyService.save(htCompany);
						goodsMember.setCompany1(htCompany);
					}else{
						goodsMember.setCompany1(htCompany1);
					}
				}
			}else{
				HtCompany htCompany = htCompanyService.get(goodsMember.getCompany1());
				if(htCompany!=null) {
					htCompany.setCompanyName(goodsMember.getComName());
					htCompanyService.save(htCompany);
				}
			}
			super.save(goodsMember);
		}catch(ServiceException e){
			e.printStackTrace();
		}
	}

	@Transactional(readOnly = false)
	public void saveNew(GoodsMember goodsMember) {
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
			/*User currentUser = UserUtils.getUser();//当前登录人
			if(currentUser != null){*/
		//String companyId =currentUser.getCompany().getId();
		try{

			boolean genOfficeFlag = false;
			Office officeCur = goodsMember.getCompany();
		    if (StringUtils.isEmpty(goodsMember.getId()) || officeCur == null || "1".equals(officeCur.getId())) {
				genOfficeFlag = true;
            } else {
				Office officeCom = goodsMember.getCompany();
				if (officeCom == null || "1".equals(officeCom.getId())) {
					genOfficeFlag = true;
				} else {
					String companyId = officeCom.getId();
					officeCom = officeService.get(companyId);
					if (officeCom == null) {
						genOfficeFlag = true;
					}
				}
			}
		    if (genOfficeFlag) {
				Office parent = new Office();
				parent.setId("1");
				Office office = new Office();
				office.setParent(parent);
				office.setType("1");
				office.setParentIds("0,1");
				office.setName(goodsMember.getComName());
                if(StringUtils.isBlank(office.getName())){
                    office.setName(goodsMember.getName());
                }
				Area area = new Area(goodsMember.getGmArea());
				office.setArea(area);
				office.setSort(30);
				office.setGrade("1");
				User user = systemService.getUser(goodsMember.getUserId());
				office.setPrimaryPerson(user);
				office.setDeputyPerson(user);
				officeService.save(office);
				goodsMember.setCompany(office);
				goodsMember.setOffice(office);
				user.setCompany(office);
				user.setOffice(office);
				user.setAccountType("1");
				systemService.saveNewUser(user);
			}
            super.save(goodsMember);
		}catch(ServiceException e){
			e.printStackTrace();
		}
	}

	@Transactional(readOnly = false)
	public void delete(GoodsMember goodsMember) {
		super.delete(goodsMember);
	}

	@Transactional(readOnly = false)
	public int deleteIds(String[] ids) {
		int result = 0;
		for (String id : ids) {
			super.delete(new GoodsMember(id));
			result ++;
		}
		return result;
	}

	/**
	 *
	 * @Title: findentityByUser
	 * @Description: 根据用户Id获取货主信息
	 * @param: @param user
	 * @param: @return
	 * @return: GoodsMember
	 * @author: chuming
	 * @date 2018年12月6日下午3:28:05
	 */
	public GoodsMember findentityByUser(User user) {
		return dao.findentityByUser(user);
	}

	public Long findCount(GoodsMember goodsMember){
		return dao.findCount(goodsMember);
	}


	/**
	 * 更新用户的openId值
	 * @param goodsMember
	 * @return List<M2mLoginUserDTO>
	 * @throws
	 */
	@Transactional(readOnly = false)
	public void updateM2mReguserOpenId(GoodsMember goodsMember) throws Exception {
		String openid = goodsMember.getOpenId();
		// 根据用户ID查询出该注册用户信息
		// 将open设置为空去查询数据
		goodsMember.setOpenId(null);
		List<GoodsMember> htDriverFileList = findList(goodsMember);
		HtAssert.notEmpty(htDriverFileList, "您的帐号登录发生异常，请联系系统管理员");
		HtAssert.outOfSize(htDriverFileList, 1, "您的帐号登录发生异常，请联系系统管理员");
		GoodsMember goodsMemberUpdate = htDriverFileList.get(0);
        goodsMemberUpdate.setOpenId(openid);
		/*if(StringUtils.isNotBlank(goodsMemberUpdate.getOpenId())){
			if(goodsMemberUpdate.getOpenId().contains(openid)){
				goodsMemberUpdate.setOpenId(goodsMemberUpdate.getOpenId());
			}else{
				goodsMemberUpdate.setOpenId(goodsMemberUpdate.getOpenId()+","+openid);
			}
		}else{
			goodsMemberUpdate.setOpenId(openid);
		}*/
		super.save(goodsMemberUpdate);
	}

	public GoodsMember findByUserid(String userId){
		return dao.findByUserid(userId);
	}

	public GoodsMember getByLoginName(String username) {
		return dao.getByMobile(username);
	}

	public GoodsMember getByLoginId(String username) {
		return dao.findByUserid(username);
	}

	public GoodsMember getUserByLoginName(String username) {
		return dao.getByLoginName(username);
	}

	@Transactional(readOnly = false)
	public void updateStatus(GoodsMember goodsMember) {
		dao.updateStatus(goodsMember);
	}

	/**
	 * 设置货主等级
	 * @param goodsMember
	 * @return
	 */
	@Transactional(readOnly = false)
	public int updateMemberLevel(GoodsMember goodsMember) {
		return dao.updateMemberLevel(goodsMember);
	}

//	/**
//	 * 货主 审核通过后，将企业名称与个人信息的名称进行同步
//	 */
//	@Transactional(readOnly = false)
//	public void updateStatusNew(GoodsMember goodsMember) {
//		userDao.updateNameByUserId(goodsMember.getUser().getId(),goodsMember.getComName());
//		//清除用户缓存
//		UserUtils.clearCache(goodsMember.getUser());
//		if (goodsMember.getUser() != null) {
//			UserUtils.clearUserMenuInfo(goodsMember.getUser().getId());//清除指定用户菜单信息
//		}
//		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
//			// 在事务提交之后执行的代码块（方法）  此处使用TransactionSynchronizationAdapter，其实在Spring5后直接使用接口也很方便了~
//			@Override
//			public void afterCommit() {
//				//异步发送微信消息
//				ThreadPoolManager.getsInstance().execute(()->{
//					WeixinMessageService weixinMessageService = SpringContextHolder.getBean(WeixinMessageService.class);
//					weixinMessageService.sendWxCheckMsg(goodsMember.getUser().getId());
//				});
//			}
//		});
//	}

	public int uniqSocialCode(@Param("unifiedSocialCreditCode") String unifiedSocialCreditCode, @Param("id") String id){
		return dao.uniqSocialCode(unifiedSocialCreditCode, id);
	}

	public int comNameCheck(@Param("comName") String comName, @Param("id") String id){
		return dao.comNameCheck(comName,id);
	}

	@Transactional(readOnly = false)
	public void save1(GoodsMember goodsMember) {
		User user = systemService.getUser(goodsMember.getUser().getId());
		// 获取企业用户单位和企业管理员角色
		Role r = systemService.getRoleByEnname("goodsMember");
		List<Role> roleList= null;
		roleList = Lists.newArrayList();
		if(user == null){
			user = new User();
			// 是否允许登录
			user.setLoginFlag("y");
			// 注册人员
			user.setUserType("1");
			user.setUserIdentity("2");
			user.setMobile(goodsMember.getUser().getMobile());
			user.setNo(goodsMember.getUser().getMobile());
			user.setLoginName(goodsMember.getUser().getLoginName());
			user.setPassword(SystemService.entryptPassword(goodsMember.getUser().getPassword()));
			user.setOpenid(goodsMember.getOpenId());
			//user.setName("货主");
			user.setEmail("");
			user.setPhone(goodsMember.getUser().getMobile());
			Office parent = new Office();
			parent.setId("0");
			Office office = new Office();
			office.setParent(parent);
			office.setType("");
			List<Office> officeList = officeService.findListOnly(office);
			if(officeList!=null && officeList.size()!=0){
				office = officeList.get(0);
				if(office!=null && office.getId()!=null){
					user.setCompany(office);
					user.setOffice(office);
					goodsMember.setOffice(office);
					goodsMember.setCompany(office);
				}else{
					Office office1 = new Office();
					office1.setId("1");
					user.setCompany(office1);
					user.setOffice(office1);
					goodsMember.setOffice(office1);
					goodsMember.setCompany(office1);
				}
			}
			roleList.add(r);
			user.setRoleList(roleList);
		}
		goodsMember.setName(goodsMember.getContactsName());
		try{
			systemService.saveUser(user);
			goodsMember.setUser(user);
		}catch(ServiceException e){
			System.out.println(e.getMessage());
		}
		super.save(goodsMember);
	}

	/**
	 * 根据客户Id获取货主信息
	 * @param customId
	 * @return
	 */
	public GoodsMember getByCompany1Id(String customId) {
		return dao.getByCompany1Id(customId);
	}



	/**
	 * @Description 货主审批状态查询
	 * @Author wlxiang
	 * @Date 17:26 2023/6/5
	 * @Param
	 * @param id
	 * @param userId
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public Map<String,Object> selectAuditInfoById(String id,String userId){
		return  dao.selectAuditInfoById(id,userId);
	};

	/**
	 * @Description MP货主详情
	 * @Author wlxiang
	 * @Date 10:26 2023/6/7
	 * @Param
	 * @param id
	 * @param userId
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public Map<String,Object> selectGoodsMemberInfoById(String id,String userId){
		return  dao.selectGoodsMemberInfoById(id,userId);
	};
	
	/**
	 * @author llh
	 * @date 2023/6/20
	 * @return java.util.Map<java.lang.String,java.lang.Integer>
	 * @description 小程序获取货主运单数据统计信息      
	 */
	public Map<String,Integer> getGoodsData(String companyId,String status,String startDate,String endDate){
		return goodsMemberDao.getGoodsData(companyId,status,startDate,endDate);
	}
}